/**
 *
 *
 *
 *
 *
 */

package org.sxp.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.sxp.common.cache.CCacheManager;
import org.sxp.common.utils.PageUtils;
import org.sxp.common.utils.Query;
import org.sxp.modules.sys.dao.SysDictDao;
import org.sxp.modules.sys.entity.SysDictEntity;
import org.sxp.modules.sys.service.SysDictService;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;


@Service("sysDictService")
public class SysDictServiceImpl extends ServiceImpl<SysDictDao, SysDictEntity> implements SysDictService {

    @Autowired
    CCacheManager cCacheManager;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String name = (String)params.get("name");

        IPage<SysDictEntity> page = this.page(
            new Query<SysDictEntity>().getPage(params),
            new QueryWrapper<SysDictEntity>()
                .like(StringUtils.isNotBlank(name),"name", name)
        );

        return new PageUtils(page);
    }

    private String cacheKey = "dict";
    @Override
    public String getValueByCode(String type, String code){
        SysDictEntity dictEntity = cCacheManager.get(cacheKey, type+"_"+code, SysDictEntity.class);
        if(dictEntity == null){
            Map<String, Object> param = new HashMap<String, Object>(16);
            param.put("type", type);
            param.put("code", code);
            dictEntity = getOne(new QueryWrapper<SysDictEntity>().eq("type", type).eq("code", code));
            if(dictEntity != null){
                return dictEntity.getValue();
            }
            return "";
        }else{
            return dictEntity.getValue();
        }
    }

    @Override
    public boolean updateById(SysDictEntity entity) {
        cCacheManager.put(cacheKey, entity.getType()+"_"+entity.getCode(), entity);
        return super.updateById(entity);
    }

    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        for(Serializable id : idList){
            SysDictEntity entity = getById(id);
            if(entity != null){
                cCacheManager.evict(cacheKey, entity.getType()+"_"+entity.getCode());
            }
        }
        return super.removeByIds(idList);
    }
}
